package com.showtao.front.service;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletContext;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.ServletContextAware;

import com.showtao.common.constant.ApplicationConstant;

@Component
public class UploadedFileHandler implements ServletContextAware {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(UploadedFileHandler.class);
	
	private ServletContext sc;
	
	public String putTemp(File file) throws IOException{
		String tempDir = sc.getRealPath(ApplicationConstant.UPLOAD_TEMP_FOLDER);
		LOGGER.debug("start to copy uploaded file into temp folder: " + tempDir);
		FileUtils.copyFileToDirectory(file, new File(tempDir));
		return ApplicationConstant.UPLOAD_TEMP_URI + '/' + FilenameUtils.getName(file.getAbsolutePath());
	}
	
	public String putTemp(InputStream is, String fileName) throws IOException{
		String tempDir = sc.getRealPath(ApplicationConstant.UPLOAD_TEMP_FOLDER);
		LOGGER.debug("start to copy uploaded file into temp folder: " + tempDir);
		FileUtils.copyInputStreamToFile(is, new File(tempDir + '/' + fileName));
		return ApplicationConstant.UPLOAD_TEMP_URI + '/' + FilenameUtils.getName(fileName);
	}
	
	public String put(File file) throws IOException{
		String dir = sc.getRealPath(ApplicationConstant.FILE_FOLDER);
		LOGGER.debug("start to copy file into resource folder: " + dir);
		FileUtils.copyFileToDirectory(file, new File(dir));
		return ApplicationConstant.FILE_URI + '/' + FilenameUtils.getName(file.getAbsolutePath());
	}

	@Override
	public void setServletContext(ServletContext sc) {
		this.sc = sc;
	}
	
}
